package com.sgb.kjwl.view.ui.activity.manage

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.Window
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.blankj.utilcode.util.SizeUtils
import com.gyf.barlibrary.ImmersionBar
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsitePostInquiryBinding
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent
import com.sgb.kjwl.di.manage.EnterpriseManageModule
import com.swgk.core.util.PickSelectEntity
import com.sgb.kjwl.model.entity.manage.UserInquiryEntity
import com.sgb.kjwl.view.ui.adapter.manage.AddViewAdapter
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter
import com.sgb.kjwl.viewmodel.manage.WebSiteInquiryModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.customview.ItemInputTextView
import com.swgk.core.util.ClickUtils
import com.swgk.core.util.MToast
import com.swgk.core.util.SharedPreferenceUtil
import java.io.File
import javax.inject.Inject

class WebSitePostInquiryActivity  : WebSiteBuildBaseActivity(), ItemInputTextView.OnWholeItemClickListener {
    @Inject
    lateinit var mModel : WebSiteInquiryModel

    private lateinit var mBinging : ActivityWebsitePostInquiryBinding

    //图片上传
    private lateinit var  mImageAdapter: ImageAdapter
    var imgTotal = 0
    private var currentImgNum = 0

    private val uploadImgList: ArrayList<UserInquiryEntity.Companion.FileInfoEntity> = ArrayList()
    lateinit var mFileInfoEntity : UserInquiryEntity.Companion.FileInfoEntity
    private val fileList: ArrayList<File> = ArrayList()
    private val urls: ArrayList<UserInquiryEntity.Companion.FileInfoEntity> = ArrayList()

    //函询类型
    private val mInquiryTypes = ArrayList<PickSelectEntity<*>>()

    private lateinit var mAddViewAdapter: AddViewAdapter

    private val mInquiryPostEntity  = UserInquiryEntity()//提交对象

    private val mReceiverEntity = UserInquiryEntity.Companion.ReceiveDTOEntity()//向谁函询的信息

    private var mWebSiteName = ""//网站名称
    private var mWebSiteNo = "" //函询的网站no
    private var mWebSiteType = WebsiteInfoActivity.WEBSITE_FOR_COMPANY//网站类型 默认企业
    private var mUserNo : String ?= null//函询接收人（团队）


    companion object{
        const val KEY_WEBSITE_TYPE = "key_website_type"
        const val KEY_WEBSITE_NO = "key_website_no"
        const val KEY_WEBSITE_NAME = "KEY_WEBSITE_NAME"
        const val KET_WEBSITE_USERNO = "key_website_userno"

        fun start(context: Context?, webSiteName : String, webSiteNo : String, webSiteType : Int){
            val intent = Intent(context, WebSitePostInquiryActivity::class.java)
            intent.putExtra(KEY_WEBSITE_NAME, webSiteName)
            intent.putExtra(KEY_WEBSITE_NO, webSiteNo)
            intent.putExtra(KEY_WEBSITE_TYPE, webSiteType)
            context!!.startActivity(intent)
        }

        //团队、组织专用
        fun start(context: Context?, webSiteName : String, webSiteNo : String, webSiteType : Int, userNo : String){
            val intent = Intent(context, WebSitePostInquiryActivity::class.java)
            intent.putExtra(KEY_WEBSITE_NAME, webSiteName)
            intent.putExtra(KEY_WEBSITE_NO, webSiteNo)
            intent.putExtra(KEY_WEBSITE_TYPE, webSiteType)
            intent.putExtra(KET_WEBSITE_USERNO, userNo)
            context!!.startActivity(intent)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
            .enterpriseManageModule(EnterpriseManageModule(this)).build().inject(this)
    }

    override fun initView() {
        if (intent != null){
           mWebSiteName = intent.getStringExtra(KEY_WEBSITE_NAME)!!
           mWebSiteNo = intent.getStringExtra(KEY_WEBSITE_NO)!!
           mWebSiteType = intent.getIntExtra(KEY_WEBSITE_TYPE, WebsiteInfoActivity.WEBSITE_FOR_COMPANY)
           mUserNo = intent.getStringExtra(KET_WEBSITE_USERNO)
        }
        mBinging =  DataBindingUtil.setContentView(this, R.layout.activity_website_post_inquiry)
        mBinging.include.titleView.text = "发起函询"
        mBinging.include.ivBack.setOnClickListener(this)
        mImageAdapter = ImageAdapter(this, null, null, 5)
        mBinging.recyclerView.layoutManager = GridLayoutManager(this, 4)
        mBinging.recyclerView.adapter = mImageAdapter
        mBinging.tvSave.setOnClickListener(this)
        mAddViewAdapter = AddViewAdapter(this)
        mBinging.addView.setAdapter(mAddViewAdapter)
        mBinging.itemTvInquiryType.setOnWholeItemClickListener(this)
        mBinging.itemTvInquiryType.visibility = if (mWebSiteType == 2 || mWebSiteType == 3) View.GONE else View.VISIBLE
        mModel.inquiryTypes.observe(this, {
            if (it.isNotEmpty()){
                mInquiryTypes.clear()
                mInquiryTypes.addAll(it)
                showSelect()
            }
        })
        mBinging.viewModel = mInquiryPostEntity
        mModel.message.observe(this, {
            if (!TextUtils.isEmpty(it)){
                MToast.showToast(this, it)
                finish()
            }
        })

        if (mWebSiteType == WebsiteInfoActivity.WEBSITE_FOR_COMPANY){ //企业
            mInquiryPostEntity.siteNo =
                SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
            mReceiverEntity.answerCompanyName = mWebSiteName
            mReceiverEntity.answerCompanyNo = mWebSiteNo
        } else if (mWebSiteType == WebsiteInfoActivity.WEBSITE_FOR_PERSONAL){//个人
            mInquiryPostEntity.siteNo =
                SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
            mReceiverEntity.answerUserName = mWebSiteName
            mReceiverEntity.answerUserNo = mWebSiteNo
        } else if (mWebSiteType == WebsiteInfoActivity.WEBSITE_FOR_TEAM){//团队
            mInquiryPostEntity.siteNo =
                SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
            mReceiverEntity.answerTeamName = mWebSiteName
            mReceiverEntity.answerTeamNo = mWebSiteNo
            if (!TextUtils.isEmpty(mUserNo)) {
                mReceiverEntity.answerUserNo = mUserNo!!
            }
            //mInquiryPostEntity.companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "")
        } else if (mWebSiteType == WebsiteInfoActivity.WEBSITE_FOR_ORGANIZE){//组织
            mInquiryPostEntity.siteNo =
                SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
            mReceiverEntity.answerOrganizeName = mWebSiteName
            mReceiverEntity.answerOrganizeNo = mWebSiteNo
            if (!TextUtils.isEmpty(mUserNo)) {
                mReceiverEntity.answerUserNo = mUserNo!!
            }
        }
        mReceiverEntity.answerUserType = mWebSiteType
        mInquiryPostEntity.receiveDTO = mReceiverEntity
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v!!.id) {
            R.id.iv_back -> {
                finish()
            }
            R.id.tv_save -> {
                if (ClickUtils.isDoubleClick()){
                    return
                }
                if (mImageAdapter.fileList.size != 0) {
                    currentImgNum = 0
                    uploadImgList.clear()
                    imgTotal = mImageAdapter.fileList.size
                    mModel.uploadMutiFileModel(this,
                        mImageAdapter.fileList[currentImgNum], 0, currentImgNum + 1
                    )
                } else {
                    uploadImgSuccess(mImageAdapter.getfileInfos(), 1)
                }
            }
        }


    }

    //图片单张上传
    fun uploadRefresh(url: String, name : String = "", type: Int) {
        mFileInfoEntity = UserInquiryEntity.Companion.FileInfoEntity();
        mFileInfoEntity.fileUrl = url
        mFileInfoEntity.name = name
        uploadImgList.add(mFileInfoEntity)
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type)
        } else {
            currentImgNum++
            mModel.uploadMutiFileModel(this, mImageAdapter.fileList[currentImgNum], 0, currentImgNum + 1)
        }
    }

    /**
     * urls 上传成功的urls  或者是网络图片地址
     * type == 0 网络上传
     */
    private val mUpLoadUrls = ArrayList<UserInquiryEntity.Companion.FileInfoEntity>()
    fun uploadImgSuccess(urls : List<UserInquiryEntity.Companion.FileInfoEntity>?, type : Int){
        if (urls == null){
            return
        }
        //拼接图片url
        mUpLoadUrls.clear()
        mUpLoadUrls.addAll(urls)
        //if (urls.isNotEmpty()){
//            val sb = StringBuilder("")
//            for (url in urls) {
//                sb.append(url).append(",")
//            }
            //mInquiryPostEntity.filedList = sb.substring(0, sb.length - 1)
        //}
        mInquiryPostEntity.filedList = mUpLoadUrls.toString()
        if (mWebSiteType != 2 && TextUtils.isEmpty(mInquiryPostEntity.questionUserTypeName)){//团队没有函询
            MToast.showToast(this, "请选择函询类型")
            return
        }
        if (TextUtils.isEmpty(mInquiryPostEntity.questionMatters)){
            MToast.showToast(this, "请输入疑问事项")
            return
        }
        if (mInquiryPostEntity.questionMatters.length < 5 || mInquiryPostEntity.questionMatters.length > 200){
            MToast.showToast(this, "请输入最少5个字，最多200字")
            return
        }
        mInquiryPostEntity.customFieldList = mBinging.addView.getDate()
        mModel.postInquiry(this, mInquiryPostEntity)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) { // 图片结果回调
                val selectList = PictureSelector.obtainMultipleResult(data)
                fileList.clear()
                urls.clear()
                for (localMedia in selectList) {
                    val file = File(localMedia.realPath)
                    fileList.add(file)
                    mFileInfoEntity = UserInquiryEntity.Companion.FileInfoEntity();
                    mFileInfoEntity.fileUrl = localMedia.realPath
                    mFileInfoEntity.name = localMedia.fileName
                    urls.add(mFileInfoEntity)
                }
                mImageAdapter.setData(selectList, urls)
                mImageAdapter.fileList = fileList
            }
        }
    }

    override fun OnWholeItemClick(view: View?) {
        when(view!!.id){
            R.id.item_tv_inquiry_type -> {
                if (mInquiryTypes.isEmpty()){
                    mModel.getAdminInquiryTypes(this)
                } else {
                   showSelect()
                }

            }
        }
    }

    fun showSelect() {
        val optionsPickerView = OptionsPickerBuilder(this, object: OnOptionsSelectListener {
            override fun onOptionsSelect(options1: Int, options2: Int, options3: Int, v: View?) {
               mBinging.itemTvInquiryType.content =  mInquiryTypes[options1].projectscale
               mInquiryPostEntity.questionUserTypeName = mInquiryTypes[options1].projectscale
                try {
                    mInquiryPostEntity.enquiryType = mInquiryTypes[options1].no.toInt()
                } catch (e : NumberFormatException){

                }
            }
        }).setCancelText("取消").setSubCalSize(15)
            .setCancelColor(resources.getColor(R.color.color_title_medium))
            .setTitleText("请选择函询类型")
            .setTitleColor(resources.getColor(R.color.color_tab_three)).setTitleSize(15)
            .setSubmitText("确定")
            .setSubmitColor(resources.getColor(R.color.color_main)).build<PickSelectEntity<*>>()
        optionsPickerView.setPicker(mInquiryTypes)
        optionsPickerView.setSelectOptions(0)
        optionsPickerView.show()
    }

}